package com.las.bot.event;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONObject;
import com.las.annotation.WxEvent;
import com.las.bot.dao.WxMsgDao;
import com.las.enums.WxMsgCallBackEnum;
import com.las.strategy.wxhandle.AbstractWxBotMsgHandler;
import com.las.utils.EmojiUtil;
import com.model.WxMsg;
import com.utils.ThreadUtil;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Date;
import java.util.concurrent.ThreadPoolExecutor;

@WxEvent(event = WxMsgCallBackEnum.WX_FRIEND_MSG)
public class WxCusEvent extends AbstractWxBotMsgHandler {

    private static Logger logger = Logger.getLogger(WxCusEvent.class);

    private ThreadPoolExecutor executor = ThreadUtil.getPool();

    @Autowired
    private WxMsgDao wxMsgDao;


    public void exec() {
        JSONObject msgData = getMsgData();
        logger.info("收到微信消息：" + msgData.toJSONString());
        String data;
        String content = msgData.getString("content");
        if (StrUtil.isBlank(content)) {
            return;
        }
        if (content.startsWith("＃")) {
            data = "#" + content.substring(1);
        } else {
            data = content;
        }
        String receiver = msgData.getString("receiver");
        String sender = msgData.getString("sender");
        int type = msgData.getInteger("type");
        String wxId = null;
        if (StrUtil.isNotBlank(receiver)) {
            if ("self".equals(receiver)) {
                wxId = sender;
            } else if (receiver.endsWith("@chatroom")) {
                wxId = receiver;
            }
        }
        if (null != wxId) {
            exeCommand(wxId, data);
        } else {
            if ("self".equals(sender)) {
                //我私发给好友
                if (StrUtil.isNotBlank(receiver)) {
                    exeCommand(receiver, data);
                }
            } else {
                //并且还需要判断sender 和 receiver 都为空，只允许是机器人本身特殊为了自身触发指令而设计
                if (StrUtil.isBlank(receiver) && StrUtil.isBlank(sender) && data.endsWith("@chatroom")) {
                    String[] sp = data.split("AT");
                    if (sp.length == 2) {
                        String comData = sp[0].trim();
                        String gId = sp[1].trim();
                        exeCommand(gId, comData);
                    }
                }
            }
        }
        String finalWxId = wxId;
        executor.execute(() -> {
            logger.info("微信DAO对象：" + wxMsgDao);
            WxMsg wxMsg = new WxMsg();
            wxMsg.setWxId(finalWxId);
            wxMsg.setSender(sender);
            wxMsg.setReceiver(receiver);
            wxMsg.setType(type);
            wxMsg.setContent(EmojiUtil.emojiChange(data));
            wxMsg.setJsonData(msgData.toJSONString());
            wxMsg.setCreateTime(new Date());
            wxMsgDao.saveOrUpdate(wxMsg);
        });
    }
}
